package com.laze.mywanandroid.ui.main

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.laze.mywanandroid.R
import com.laze.mywanandroid.base.BaseActivity
import com.laze.mywanandroid.ui.main.fragment.demo.DemoFragment
import com.laze.mywanandroid.ui.main.fragment.home.HomeFragment
import com.laze.mywanandroid.ui.main.fragment.project.ProjectFragment
import kotlinx.android.synthetic.main.activity_base_top_bar.*
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : BaseActivity() {
    private lateinit var fragments: Map<Int, Fragment>

    override fun getContentView(): Int  = R.layout.activity_main

    override fun getTitleText(): String = "主页"

    override fun initView() {
        toolbar.visibility = View.GONE

        fragments = mapOf(
            R.id.bottomHome to HomeFragment.newInstance(),
            R.id.bottomProject to ProjectFragment.newInstance(),
            R.id.bottomDemo to DemoFragment.newInstance()
        )

        bottomNavigation.run {
            setOnNavigationItemSelectedListener {
                showFragment(it.itemId)
                true
            }
            supportFragmentManager.beginTransaction().apply {
                add(R.id.flMain, HomeFragment.newInstance())
            }.commit()
        }
    }

    override fun initData(savedInstanceState: Bundle?) {

    }

    private fun showFragment(itemId: Int) {
        //当前fragment
        val currentFragment = supportFragmentManager.fragments.find {
            it.isVisible /*&& it in fragments.values 因为一开始展示了一个不再fragments里面的homefragment，要一起隐藏*/
        }
        val taggerFragment = fragments.entries.find { it.key == itemId }?.value
        supportFragmentManager.beginTransaction().apply {
            currentFragment?.let { if (it.isVisible) hide(it) }
            taggerFragment?.let {
                if (it.isAdded) show(it) else add(R.id.flMain, it)
            }
        }.commit()
    }

}